package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.io.LineProcessor;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.user.OrderController;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.OnReactiveWebApplication;
import springfox.documentation.spring.web.plugins.SpringIntegrationPluginNotPresentInClassPathCondition;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShopcartMapper shopcartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisTemplate redisTemplate;

    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        String detailAddress = addressBook.getProvinceName()+" " + addressBook.getCityName()+" " + addressBook.getDistrictName()+" " + addressBook.getDetail();
        if (addressBook == null) {
            throw new AddressBookBusinessException("地址有误");
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        //对不同的用户进行查询
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        //查询购物车信息
        List<ShoppingCart> shoppingCartList = shopcartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException("购物车为空，不能下单");
        }
        //在没有支付之前现将购物车信息插入数据库，支付以后在进行更新购物车
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置订单状态
        orders.setPayStatus(Orders.UN_PAID);
        //用户下单，预付款状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置手机号
        orders.setPhone(addressBook.getPhone());
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //设置地址
        orders.setAddress(detailAddress);
        //设置下单用户id,确定是哪位用户下的订单
        orders.setUserId(userId);


        orderMapper.insert(orders);
        Long orderId = orders.getId();
        List<OrderDetail>orderDetailList =new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList){
            OrderDetail orderDetail = new OrderDetail();//订单详情
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        shopcartMapper.delete(userId);
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        log.info("订单支付：{}", ordersPaymentDTO);
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;
        LocalDateTime check_out_time = LocalDateTime.now();
        String order_number = ordersPaymentDTO.getOrderNumber();
        Orders orders = orderMapper.SelectOrder(order_number);
        orderMapper.updateStatus(OrderStatus,OrderPaidStatus,check_out_time, order_number);
        //服务器端向管理用户端发送消息
        Long orderId=orders.getId();

        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orderId);
        map.put("content","订单号"+order_number);
        String message = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(message);
        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }


    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }


    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getOrderById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    public void cancel(Long id) {
        // 查询当前订单的状态，是否可取消
        Orders orders = orderMapper.getOrderById(id);
        if (orders.getStatus() == Orders.PENDING_PAYMENT || orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            orderMapper.updateStatus2(id, Orders.CANCELLED, LocalDateTime.now());
        }else{
            throw new OrderBusinessException("订单不可取消");
        }
    }
    //客户催单
    public void reminder(Long id) {
        Orders orders = orderMapper.getOrderById(id);
        Map map=new HashMap();
        //服务器端向管理用户端发送消息
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orders.getNumber());
        String message = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(message);
    }
    //管理端后台分页查询
    public PageResult pageQuery(Integer page, Integer pageSize, String number, String beginTime, String endTime, Integer status,String phone) {
        //number是订单号，ststus是订单状态,beginTime和endTime表示在这个范围内的订单下单时间
        PageHelper.startPage(page, pageSize);
        //查询数据信息,并查询oreDetail表的菜品信息，将查询到的菜品信息封装到orderVO中
        //1.先查询order表信息
        Page<Orders> pages = orderMapper.page2Query(number, beginTime, endTime, status,phone);
        //获得查询Orders表的信息
        List<Orders> ordersList =pages.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders orders : ordersList) {
            Long orderId = orders.getId();
            List<String> orderDishes = orderMapper.getOrderDishes(orderId);
            OrderVO orderVO = new OrderVO();
            orderVO.setOrderDishes(String.join(",", orderDishes));
            BeanUtils.copyProperties(orders, orderVO);
            orderVOList.add(orderVO);
        }
        return new PageResult(pages.getTotal(), orderVOList);
    }
    //商家接单
    public void confirm(OrdersDTO ordersDTO) {
        orderMapper.updateStatus3(ordersDTO.getId(), Orders.CONFIRMED);
    }
    //商家取消订单
    public void cancel2(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getOrderById(ordersCancelDTO.getId());
        //判断是否可以取消，已接单，派送中，已完成不可以取消
        if (orders.getStatus() == Orders.CONFIRMED || orders.getStatus() == Orders.DELIVERY_IN_PROGRESS || orders.getStatus() == Orders.COMPLETED) {
            throw new OrderBusinessException("订单不可取消");
        }
        orderMapper.updateStatus4(ordersCancelDTO.getId(), Orders.CANCELLED, ordersCancelDTO.getCancelReason(), LocalDateTime.now());
    }

    public OrderStatisticsVO statistics() {
        List<OrderStatisticsDTO>map =new ArrayList<>();
        map=orderMapper.statisticscs();
        log.info("map:{}",map);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        for (OrderStatisticsDTO stat : map) {
            switch (stat.getStatus()) {
                case 2:
                    orderStatisticsVO.setToBeConfirmed(stat.getNumber());
                    break;
                case 3:
                    orderStatisticsVO.setConfirmed(stat.getNumber());
                    break;
                case 4:
                    orderStatisticsVO.setDeliveryInProgress(stat.getNumber());
                    break;
            }
        }
        return orderStatisticsVO;
    }

    public void delivery(Long id) {
        orderMapper.updateStatus5(id, Orders.DELIVERY_IN_PROGRESS);
    }

    public void complete(Long id) {
        orderMapper.updateStatus5(id, Orders.COMPLETED);
    }

    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.reject(ordersRejectionDTO);
    }
}
